<?php
global $db;
global $db_connection;
$db_connection = mysqli_connect('localhost','root', '', 'travel');

if(mysqli_connect_errno()) 
{
    die('Database Server Error!');
}
mysqli_query($db_connection, "SET NAMES UTF8");
/**
 *
 * @return mysqli_connection 
 */
function getDB()
{
    global $db_connection;
	return $db_connection;
}

function getList($table = '', $fields = '*', $conditions = '1', $order_by = '1', $limit = 30)
{
    $list = array();
    $columns = '';
    if(is_array($fields))
    {
        foreach ($fields as $f)
        {
            $columns .= " $f,";
        }
        $columns = substr($columns, 0, strlen($columns) - 1);
    }
    $sql = "SELECT " . (($fields == '*')?$fields:$columns) . 
            " FROM " . $table . 
            " WHERE " . $conditions . " ORDER BY " . $order_by . " LIMIT $limit";

    $result = mysqli_query(getDB(), $sql);
    if($result !== FALSE and mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
        {
            $list[] = $row;
        }
    }
    return $list;
}

function insertItem($table = '', $fields = '', $values = '')
{
    $list = array();
    $columns = '';
    if(is_array($fields))
    {
        foreach ($fields as $f)
        {
            $columns .= " `$f`,";
        }
        $columns = substr($columns, 0, strlen($columns) - 1);
    }
    else
    {
        $columns = $fields;
    }
    $val = '';
    if(is_array($values))
    {
        foreach ($values as $v)
        {
            $val .= " '{$v}',";
        }
        $val = substr($val, 0, strlen($val) - 1);
    }
    $sql = "INSERT INTO `{$table}`({$columns}) VALUES({$val})";
    
    return mysqli_query(getDB(), $sql);
}

?>